package com.lly.bigdata.bgayx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lly.bigdata.bgayx.common.constants.Constants;
import com.lly.bigdata.bgayx.common.redis.RedisCache;
import com.lly.bigdata.bgayx.common.text.Convert;
import com.lly.bigdata.bgayx.common.utils.StringUtils;
import com.lly.bigdata.bgayx.entity.SysConfig;
import com.lly.bigdata.bgayx.mapper.SysConfigMapper;
import com.lly.bigdata.bgayx.service.ISysConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 配置文件管理页面
 * </p>
 *
 * @author Auto-generator
 * @since 2022-03-23
 */
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements ISysConfigService {


    @Autowired
    private RedisCache redisCache;


    /**
     * 获取验证码开关
     *
     * @return true开启，false关闭
     */
    @Override
    public boolean selectCaptchaOnOff() {
        String captchaOnOff = selectConfigByKey("sys.account.captchaOnOff");
        if (StringUtils.isEmpty(captchaOnOff)) {
            return true;
        }
        return Convert.toBool(captchaOnOff);
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = Convert.toStr(redisCache.getCacheObject(getCacheKey(configKey)));
        if (StringUtils.isNotEmpty(configValue)) {
            return configValue;
        }
        SysConfig config = new SysConfig();
        config.setConfigKey(configKey);
        QueryWrapper<SysConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysConfig::getConfigKey, configKey);
        SysConfig retConfig = this.baseMapper.selectOne(queryWrapper);
        if (StringUtils.isNotNull(retConfig)) {
            redisCache.setCacheObject(getCacheKey(configKey), retConfig.getConfigValue());
            return retConfig.getConfigValue();
        }
        return StringUtils.EMPTY;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.SYS_CONFIG_KEY + configKey;
    }
}
